//
//  YXLoginAndRegistViewController.m
//  CreditCard
//
//  Created by 杨旭 on 2017/12/26.
//  Copyright © 2017年 杨旭. All rights reserved.
//

#import "YXLoginAndRegistViewController.h"
#import "YXLoginView.h"
#import "YXRegistView.h"
#import "YXForgotTableView.h"
#import "YXLeftMenuTableViewController.h"
#import "YXHomeViewController.h"
#import "YXDrawerViewController.h"
@interface YXLoginAndRegistViewController ()
@property (nonatomic ,strong) YXLoginView *loginView;
@property (nonatomic ,strong) YXRegistView *registView;
@end

@implementation YXLoginAndRegistViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated ];
    if (self.typeView ==LogingView || self.typeView == RegistView) {
        self.navigationController.navigationBarHidden = YES;
    }else {
        self.navigationController.navigationBarHidden = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createUI];
}

- (void)createUI {
    switch (self.typeView) {
        case LogingView:
        {
            YXLoginView *loginView = [[YXLoginView alloc] initWithFrame:self.view.bounds];
            [self.view addSubview:loginView];
            self.loginView = loginView;
            [loginView setSelectBtnClickBlock:^(NSInteger index) {
                if (index == 0) { // 忘记密码
                    self.navigationController.navigationBarHidden = NO;
                    YXLoginAndRegistViewController *forgetView = [[YXLoginAndRegistViewController alloc] init];
                    forgetView.title = @"重置登录密码";
                    forgetView.typeView = ForgetView;
                    
                    [self.navigationController pushViewController:forgetView animated:YES];
                    
                }else if (index == 1) {   // 注册
                    self.navigationController.navigationBarHidden = YES;

                    YXLoginAndRegistViewController *registVC = [[YXLoginAndRegistViewController alloc] init];
                    registVC.typeView = RegistView;
                    [self.navigationController pushViewController:registVC animated:YES];
                  
                }else {  // 登录
                    
//                    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
//                    YXLeftMenuTableViewController *leftMenuVC = [[YXLeftMenuTableViewController alloc] init];
//                    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//                    YXHomeViewController *homeVC = sb.instantiateInitialViewController;
//                    keyWindow.rootViewController = [YXDrawerViewController drawerVcWithMainVC:homeVC leftMenuVc:leftMenuVC leftWidth:300];
                    
                    if (self.loginView.accountTF.text.length == 0 || self.loginView.passwordTF.text.length == 0) {
                        [self showTostMessage:@"账号密码不能为空"];
                    }else {
                        
                         [[NSUserDefaults standardUserDefaults] setObject:self.loginView.accountTF.text forKey:kPHONE];
                        
                        [SVProgressHUD showWithStatus:@"登录中..."];
                        
                        //  http://121.196.210.134:8082/mpos/wx/login.do?account=admin&password=0e9212587d373ca58e9bada0c15e6fe4
                        NSString *urlStr = @"login.do";
                        NSString *pwd = [[self passwordToMD5:self.loginView.passwordTF.text] lowercaseString];
                        NSDictionary *parameter = @{@"account":self.loginView.accountTF.text,@"password":pwd};
                        [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
                            [SVProgressHUD dismiss];
                            if (REQUESTDATASUCCESS) {
                                NSLog(@"请求成功%@",responseObject);
                                
                                //每次登陆之前先清空沙盒中的用户信息
                                [YXUserInfoManager cleanUserInfo];
                                //存入
                                YXUserInfoModel *model = [[YXUserInfoModel alloc] initWithDic:responseObject[@"body"]];
                                //保存用户信息
                                [YXUserInfoManager saveUserInfoWithModel:model];
                                
                                [SVProgressHUD showSuccessWithStatus:@"登录成功！"];

                                
                                UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
                                YXLeftMenuTableViewController *leftMenuVC = [[YXLeftMenuTableViewController alloc] init];
                                UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                                YXHomeViewController *homeVC = sb.instantiateInitialViewController;
                                keyWindow.rootViewController = [YXDrawerViewController drawerVcWithMainVC:homeVC leftMenuVc:leftMenuVC leftWidth:300];

                            }else {
                                
                                [self showTostMessage:responseObject[@"msg"]];
                            }
                        } failure:^(NSError *error) {
                            [SVProgressHUD dismiss];
                            [self showTostMessage:@"账号密码错误！"];
                        }];
                        
                    }

                    
                }
            }];
        }
            break;
        case RegistView:
        {
            self.title = @"注册";
            YXRegistView *registView = [[YXRegistView alloc] initWithFrame:self.view.bounds];
            [self.view addSubview:registView];
            self.registView = registView;
            
            // 返回
            [registView setReturnBtnBlock:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
            // 发送短信验证码
            [registView setVerificationCodeBtnBlock:^(NSString *phone) {
             
                [self requestSendRegisterSmsCodePhone:phone withTitle:self.title];
                
            }];
            
            
            // 注册
            [registView setRegistBtnBlock:^(NSDictionary *dict) {
//                http://121.196.210.134:8082/mpos/wx/register.do?account=18616731923&smsCode=372822&password=123123&password2=123123&userName=18616731923
                NSString *urlStr = @"register.do";
                NSString *pwd = [[self passwordToMD5:dict[@"password"]] lowercaseString];
                NSString *pwd2 = [[self passwordToMD5:dict[@"password2"]] lowercaseString];
                NSDictionary *parameter = @{@"account":dict[@"account"],@"smsCode":dict[@"smsCode"],@"password":pwd,@"password2":pwd2,@"userName":dict[@"userName"],@"pid":dict[@"pid"]};
                [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
                    if (REQUESTDATASUCCESS) {
                        NSLog(@"请求成功：%@",responseObject);
                        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"恭喜" message:@"注册成功！" preferredStyle:(UIAlertControllerStyleAlert)];
                        
                        UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                            
                        }];
                        
                        [alertController addAction:alert];
                        
                        [self presentViewController:alertController animated:YES completion:nil];
                        [self.registView.registBtn setTitle:@"注册成功" forState:(UIControlStateNormal)];
                        
                    }
                } failure:^(NSError *error) {
                    [self showTostMessage:@"注册失败！"];

                }];
            }];
        }
            break;
        case ForgetView:
        {
            [self createLeftBarButtonItemWithImage:@"导航栏_002"];
            NSArray *titleArr = @[@"手 机 号 码",@"获取验证码",@"输入新密码",@"确认新密码"];
            NSArray *contentArr = @[@"请输入手机号码",@"请输入验证码",@"请输入密码",@"请输入密码"];
            YXForgotTableView *tableView = [[YXForgotTableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain) withTitleArr:titleArr withContentArr:contentArr];
            [self.view addSubview:tableView];
            
            // 获取验证码
            [tableView setCodeBtnClickBlock:^(NSString *phone) {
                
                [self requestSendRegisterSmsCodePhone:phone withTitle:self.title];
            }];

            // 修改密码
            [tableView setAddBtnClickBlock:^(NSDictionary *dict) {
                
                NSString *pwd = [[self passwordToMD5:dict[@"password"]] lowercaseString];
                NSString *pwd2 = [[self passwordToMD5:dict[@"password2"]] lowercaseString];
                
                if (dict[@"password"] != dict[@"password2"]) {
                    [self showTostMessage:@"两次输入密码不相同"];
                }else {
                    //  http://121.196.210.134:8082/mpos/wx/modifyPassword.do
                    NSString *urlStr = @"modifyPassword.do";
                    NSDictionary *parameter = @{@"account":dict[@"account"],@"password":pwd,@"password2":pwd2,@"smsCode":dict[@"smsCode"]};
                    [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
                        if (REQUESTDATASUCCESS) {
                            
                            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"密码设置成功！" message:@"" preferredStyle:(UIAlertControllerStyleAlert)];
                            
                            UIAlertAction *alert = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                                
                            }];
                            
                            UIAlertAction *alert1 = [UIAlertAction actionWithTitle:@"立即登录" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                                
                                [self.navigationController popViewControllerAnimated:YES];
                            }];
                            
                            [alertController addAction:alert];
                            [alertController addAction:alert1];
                            
                            [self presentViewController:alertController animated:YES completion:nil];
                        }
                    } failure:^(NSError *error) {
                        [self showTostMessage:@"修改失败！"];
                    }];
                    
                }
                

            }];
            
        }
            break;
            
        default:
            break;
    }
    
}

#pragma mark - 获取短信验证码
- (void)requestSendRegisterSmsCodePhone:(NSString *)phone withTitle:(NSString *)title {
    
    NSString *urlStr;
    if ([title isEqualToString:@"注册"]) {
//    http://121.196.210.134:8082/mpos/wx/sendRegisterSmsCode.do
          urlStr = @"sendRegisterSmsCode.do";
      
    }else {
//        http://121.196.210.134:8082/mpos/wx/sendModifySmsCode.do
          urlStr = @"sendModifySmsCode.do";
    }
    NSDictionary *parameter = @{@"phone":phone};
    [BX_NetWorkManager requestForGETWithUrl:urlStr parameter:parameter success:^(id responseObject) {
        NSLog(@"请求成功：%@",responseObject);
        if (REQUESTDATASUCCESS) {
            [self showAlertWithTitle:@"提示" Messge:@"手机短信发送成功！"];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        if ([title isEqualToString:@"注册"]) {
            [self showAlertWithTitle:@"提示" Messge:@"此号码已经被注册过"];
        }
    }];
}



@end
